package com.yupi.tangoj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.yupi.tangoj.common.ErrorCode;
import com.yupi.tangoj.constant.CommonConstant;
import com.yupi.tangoj.exception.BusinessException;
import com.yupi.tangoj.mapper.QuestionSubmitMapper;
import com.yupi.tangoj.model.dto.questionsubmit.QuestionSubmitQueryRequest;
import com.yupi.tangoj.model.entity.Question;
import com.yupi.tangoj.model.entity.QuestionSubmit;
import com.yupi.tangoj.model.entity.User;
import com.yupi.tangoj.model.vo.QuestionSubmitVO;
import com.yupi.tangoj.model.vo.QuestionVO;
import com.yupi.tangoj.model.vo.UserVO;
import com.yupi.tangoj.service.QuestionService;
import com.yupi.tangoj.service.QuestionSubmitService;
import com.yupi.tangoj.service.UserService;
import com.yupi.tangoj.utils.SqlUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
* @author 24350
* @description 针对表【questionSubmit_submit(题目提交表)】的数据库操作Service实现
* @createDate 2023-12-07 13:38:59
*/
@Service
public class QuestionSubmitServiceImpl extends ServiceImpl<QuestionSubmitMapper, QuestionSubmit>
    implements QuestionSubmitService {

    private final static Gson GSON = new Gson();

    @Resource
    private UserService userService;

    @Autowired
    private QuestionService questionService;

    @Autowired
    private QuestionSubmitMapper questionSubmitMapper;

    @Override
    public void validQuestionSubmit(QuestionSubmit questionSubmit, boolean add) {
        if (questionSubmit == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String code = questionSubmit.getCode();
        Long questionId = questionSubmit.getQuestionId();
//        Long userId = questionSubmit.getUserId();

        // 有参数则校验
        if (StringUtils.isNotBlank(code) && code.length() > 1000000) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "代码过长");
        }
        if (questionId == null ) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
    }

    /**
     * 获取查询包装类
     *
     * @param questionSubmitQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<QuestionSubmit> getQueryWrapper(QuestionSubmitQueryRequest questionSubmitQueryRequest) {
        QueryWrapper<QuestionSubmit> queryWrapper = new QueryWrapper<>();
        if (questionSubmitQueryRequest == null) {
            return queryWrapper;
        }

        Long id = questionSubmitQueryRequest.getId();
        String language = questionSubmitQueryRequest.getLanguage();
        Integer status = questionSubmitQueryRequest.getStatus();
        Long questionId = questionSubmitQueryRequest.getQuestionId();

        Long userId = questionSubmitQueryRequest.getUserId();
        String sortField = questionSubmitQueryRequest.getSortField();
        String sortOrder = questionSubmitQueryRequest.getSortOrder();

        // 拼接查询条件
        queryWrapper.like(StringUtils.isNotBlank(language), "language", language);
        queryWrapper.like(status != null, "status", status);

        queryWrapper.eq(ObjectUtils.isNotEmpty(questionId), "questionId", questionId);
        queryWrapper.eq(id != null, "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq("isDelete", false);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    @Override
    public QuestionSubmitVO getQuestionSubmitVO(QuestionSubmit questionSubmit, HttpServletRequest request) {
        QuestionSubmitVO questionSubmitVO = QuestionSubmitVO.objToVo(questionSubmit);
        Long questionId = questionSubmit.getQuestionId();

        // 1. 关联查询用户信息
        Long userId = questionSubmit.getUserId();
        User user = null;
        Question question = null;

        if (userId != null && userId > 0) {
            user = userService.getById(userId);
        }
        if (questionId != null && questionId > 0){
            question = questionService.getById(questionId);
        }

        UserVO userVO = userService.getUserVO(user);
        QuestionVO questionVO = questionService.getQuestionVO(question,request);

        questionSubmitVO.setUserVO(userVO);
        questionSubmitVO.setQuestionVO(questionVO);

        // 2. 已登录，获取用户点赞、收藏状态
//        User loginUser = userService.getLoginUserPermitNull(request);
//        if (loginUser != null) {
//            // 获取点赞
//            QueryWrapper<QuestionSubmitThumb> questionSubmitThumbQueryWrapper = new QueryWrapper<>();
//            questionSubmitThumbQueryWrapper.in("questionSubmitId", questionSubmitId);
//            questionSubmitThumbQueryWrapper.eq("userId", loginUser.getId());
//            QuestionSubmitThumb questionSubmitThumb = questionSubmitThumbMapper.selectOne(questionSubmitThumbQueryWrapper);
//            questionSubmitVO.setHasThumb(questionSubmitThumb != null);
//            // 获取收藏
//            QueryWrapper<QuestionSubmitFavour> questionSubmitFavourQueryWrapper = new QueryWrapper<>();
//            questionSubmitFavourQueryWrapper.in("questionSubmitId", questionSubmitId);
//            questionSubmitFavourQueryWrapper.eq("userId", loginUser.getId());
//            QuestionSubmitFavour questionSubmitFavour = questionSubmitFavourMapper.selectOne(questionSubmitFavourQueryWrapper);
//            questionSubmitVO.setHasFavour(questionSubmitFavour != null);
//        }
        return questionSubmitVO;
    }

    @Override
    public Page<QuestionSubmitVO> getQuestionSubmitVOPage(Page<QuestionSubmit> questionSubmitPage, HttpServletRequest request) {
        List<QuestionSubmit> questionSubmitList = questionSubmitPage.getRecords();
        Page<QuestionSubmitVO> questionSubmitVOPage = new Page<>(questionSubmitPage.getCurrent(), questionSubmitPage.getSize(), questionSubmitPage.getTotal());
        if (CollectionUtils.isEmpty(questionSubmitList)) {
            return questionSubmitVOPage;
        }
        // 1. 关联查询用户信息
        Set<Long> userIdSet = questionSubmitList.stream().map(QuestionSubmit::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));

        Set<Long> questionidSet = questionSubmitList.stream().map(QuestionSubmit::getQuestionId).collect(Collectors.toSet());
        Map<Long,List<Question>> questionIdQuestionListMap = questionService.listByIds(questionidSet).stream()
                .collect(Collectors.groupingBy(Question::getId));

        // 2. 已登录，获取用户点赞、收藏状态
        Map<Long, Boolean> questionSubmitIdHasThumbMap = new HashMap<>();
        Map<Long, Boolean> questionSubmitIdHasFavourMap = new HashMap<>();
        User loginUser = userService.getLoginUserPermitNull(request);
        if (loginUser != null) {
//            Set<Long> questionSubmitIdSet = questionSubmitList.stream().map(QuestionSubmit::getId).collect(Collectors.toSet());
//            loginUser = userService.getLoginUser(request);
//            // 获取点赞
//            QueryWrapper<QuestionSubmitThumb> questionSubmitThumbQueryWrapper = new QueryWrapper<>();
//            questionSubmitThumbQueryWrapper.in("questionSubmitId", questionSubmitIdSet);
//            questionSubmitThumbQueryWrapper.eq("userId", loginUser.getId());
//            List<QuestionSubmitThumb> questionSubmitQuestionSubmitThumbList = questionSubmitThumbMapper.selectList(questionSubmitThumbQueryWrapper);
//            questionSubmitQuestionSubmitThumbList.forEach(questionSubmitQuestionSubmitThumb -> questionSubmitIdHasThumbMap.put(questionSubmitQuestionSubmitThumb.getQuestionSubmitId(), true));
//            // 获取收藏
//            QueryWrapper<QuestionSubmitFavour> questionSubmitFavourQueryWrapper = new QueryWrapper<>();
//            questionSubmitFavourQueryWrapper.in("questionSubmitId", questionSubmitIdSet);
//            questionSubmitFavourQueryWrapper.eq("userId", loginUser.getId());
//            List<QuestionSubmitFavour> questionSubmitFavourList = questionSubmitFavourMapper.selectList(questionSubmitFavourQueryWrapper);
//            questionSubmitFavourList.forEach(questionSubmitFavour -> questionSubmitIdHasFavourMap.put(questionSubmitFavour.getQuestionSubmitId(), true));
        }
        // 填充信息
        List<QuestionSubmitVO> questionSubmitVOList = questionSubmitList.stream().map(questionSubmit -> {
            QuestionSubmitVO questionSubmitVO = QuestionSubmitVO.objToVo(questionSubmit);
            Long userId = questionSubmit.getUserId();
            Long questionId = questionSubmit.getQuestionId();

            User user = null;
            Question question = null;

            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            if (questionIdQuestionListMap.containsKey(questionId)){
                question = questionIdQuestionListMap.get(questionId).get(0);
            }


            questionSubmitVO.setUserVO(userService.getUserVO(user));
            questionSubmitVO.setQuestionVO(questionService.getQuestionVO(question,request));
//            questionSubmitVO.setHasThumb(questionSubmitIdHasThumbMap.getOrDefault(questionSubmit.getId(), false));
//            questionSubmitVO.setHasFavour(questionSubmitIdHasFavourMap.getOrDefault(questionSubmit.getId(), false));
            return questionSubmitVO;
        }).collect(Collectors.toList());


        questionSubmitVOPage.setRecords(questionSubmitVOList);
        return questionSubmitVOPage;
    }
}




